﻿using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using StoreSQLSugar_API.Models;
using StoreSQLSugar_API.Services;

namespace StoreSQLSugar_API.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class StorageRecordController : ControllerBase
    {
        private IStorageRecord _storageRecord;

        public StorageRecordController(IStorageRecord storageRecord)
        {
            _storageRecord = storageRecord;
        }

        [HttpPost("Add")]
        public ActionResult Add([FromBody] Models.StorageRecord model)
        {
            if (_storageRecord.Add(model))
            {
                return Ok(new
                {
                    Code = 200,
                    Msg = "添加成功"
                });
            }

            return Ok(new
            {
                Code = 10000,
                Msg = "添加失败"
            });
        }

            [HttpDelete("Remove")]
            public ActionResult Remove([FromBody] int RecordId)
            {
                if (_storageRecord.Delete(RecordId))
                {
                    return Ok(new
                    {
                        Code = 200,
                        Msg = "删除成功"
                    });
                }

                return Ok(new
                {
                    Code = 10000,
                    Msg = "删除失败"
                });
            }

            [HttpPut("Update")]
            public ActionResult Update([FromBody] Models.StorageRecord model)
            {
                if (model.RecordId <= 0)
                {
                    return Ok(new
                    {
                        Code = 10000,
                        Msg = "UserId参数有误，必须是大于0的整数"
                    });
                }
                if (model.LastUpdateUserId <= 0)
                {
                    return Ok(new
                    {
                        Code = 10000,
                        Msg = "LastUpdateUserId参数有误，必须是大于0的整数，且是当前登录的用户Id"
                    });
                }
                var existModel = _storageRecord.GetModel(model.RecordId);
                if (existModel == null)
                {
                    return Ok(new
                    {
                        Code = 10000,
                        Msg = "你修改的模型不存在"
                    });
                }
                var updateModel = new Models.StorageRecord()
                {
                    RecordId = model.RecordId,
                    StoreAreaId = model.StoreAreaId == null ? existModel.StoreAreaId : model.StoreAreaId,
                    ProductId = model.ProductId == null ? existModel.ProductId : model.ProductId,
                    Amount = model.Amount,
                    IncomeTime = model.IncomeTime,
                    Remark = model.Remark,
                    Status = model.Status == -1 ? existModel.Status : model.Status,
                    CreateUserId = model.CreateUserId,
                    CreateTime = DateTime.Now,
                    LastUpdateTime = DateTime.Now,
                    LastUpdateUserId = model.LastUpdateUserId
                };
                if (_storageRecord.Update(updateModel))
                {
                    return Ok(new
                    {
                        Code = 200,
                        Msg = "修改成功"
                    });
                }

                return Ok(new
                {
                    Code = 10000,
                    Msg = "修改失败"
                });
            }

            #region 其他更新方法

            /*[HttpPut("Update")]
            public ActionResult Update([FromBody] UpdateUser model)
            {
                if (model.UserId > 0)
                {
                    return Ok(new
                    {
                        Code = 10000,
                        Msg = "UserId参数有误，必须是大于0的整数"
                    });
                }
                if (model.LastUpdateUserId > 0)
                {
                    return Ok(new
                    {
                        Code = 10000,
                        Msg = "LastUpdateUserId参数有误，必须是大于0的整数，且是当前登录的用户Id"
                    });
                }
                var existModel = _todoService.GetModel(model.UserId);
                if (existModel == null)
                {
                    return Ok(new
                    {
                        Code = 10000,
                        Msg = "你修改的用户不存在"
                    });
                }
                var updateModel = new User()
                {
                    UserId = model.UserId,
                    UserName = model.UserName == null ? existModel.UserName : model.UserName,
                    Password = model.Password == null ? existModel.Password : model.Password,
                    Avatar = model.Avatar == null ? existModel.Avatar : model.Avatar,
                    Status = model.Status == null ? existModel.Status : model.Status.Value,
                    LastUpdateTime = DateTime.Now,
                    LastUpdateUserId = model.LastUpdateUserId
                };
                if (_todoService.Update(updateModel))
                {
                    return Ok(new
                    {
                        Code = 200,
                        Msg = "修改成功"
                    });
                }

                return Ok(new
                {
                    Code = 10000,
                    Msg = "修改失败"
                });
            }*/

            /*
            // 方法的[FromBody]特性修饰的参数有且只能有一个。
            [HttpPut("Update")] 
            public ActionResult Update(
                [FromBody] int userId,
                [FromQuery] string? userName,
                [FromQuery] string? password,
                [FromQuery] byte[]? avatar,
                [FromQuery] int? status,
                [FromQuery] int LastUpdateUserId)
            {
                if (userId <= 0)
                {
                    return Ok(new
                    {
                        Code = 10000,
                        Msg = "UserId参数有误，必须是大于0的整数"
                    });
                }
                if (model.LastUpdateUserId <= 0)
                {
                    return Ok(new
                    {
                        Code = 10000,
                        Msg = "LastUpdateUserId参数有误，必须是大于0的整数，且是当前登录的用户Id"
                    });
                }
                var existModel = _todoService.GetModel(userId);
                if (existModel == null)
                {
                    return Ok(new
                    {
                        Code = 10000,
                        Msg = "你修改的用户不存在"
                    });
                }
                var updateModel = new User()
                {
                    UserId = userId,
                    UserName = userName == null ? existModel.UserName : userName,
                    Password = password == null ? existModel.Password : password,
                    Avatar = avatar == null ? existModel.Avatar : avatar,
                    Status = status == null ? existModel.Status : status.Value,
                    LastUpdateTime = DateTime.Now,
                    LastUpdateUserId = lastUpdateUserId
                };
                if (_todoService.Update(updateModel))
                {
                    return Ok(new
                    {
                        Code = 200,
                        Msg = "修改成功"
                    });
                }

                return Ok(new
                {
                    Code = 10000,
                    Msg = "修改失败"
                });
            }*/

            #endregion

            [HttpGet("Get")]
            public ActionResult Get(string? Remark, int? status, DateOnly? createTimeStart, DateOnly? createTimeEnd, int pageIndex = 1, int pageSize = 10)
            {
                var exp = Expressionable.Create<Models.StorageRecord>();
                exp.AndIF(!string.IsNullOrEmpty(Remark), x => x.Remark.Contains(Remark!));
                exp.AndIF(!(status == null || status == -1), x => x.Status == status);
                exp.AndIF(createTimeStart != null, x => x.CreateTime >= DateTime.Parse(createTimeStart!.Value.ToString("yyyy-MM-dd") + " 00:00:00"));
                exp.AndIF(createTimeEnd != null, x => x.CreateTime <= DateTime.Parse(createTimeEnd!.Value.ToString("yyyy-MM-dd") + " 23:59:59"));

                var totalPage = 0;
                var list = _storageRecord.GetList(exp, out totalPage, pageIndex, pageSize);
                return Ok(new
                {
                    Code = 200,
                    Msg = "查询成功",
                    TotalPage = totalPage,
                    Data = list
                });
            }

            [HttpGet("GetAll")]
            public ActionResult Get(string? Remark, int? status, DateOnly? createTimeStart, DateOnly? createTimeEnd)
            {
                var exp = Expressionable.Create<Models.StorageRecord>();
                exp.AndIF(!string.IsNullOrEmpty(Remark), x => x.Remark.Contains(Remark!));
                exp.AndIF(!(status == null || status == -1), x => x.Status == status);
                exp.AndIF(createTimeStart != null, x => x.CreateTime >= DateTime.Parse(createTimeStart!.Value.ToString("yyyy-MM-dd") + " 00:00:00"));
                exp.AndIF(createTimeEnd != null, x => x.CreateTime <= DateTime.Parse(createTimeEnd!.Value.ToString("yyyy-MM-dd") + " 23:59:59"));
                return Ok(new
                {
                    Code = 200,
                    Msg = "查询成功",
                    Data = _storageRecord.GetListAll(exp)
                });
            }

            // 查询有两种传参方式：
            // 1。查询字符串（不优雅，有些搜索引擎支持不友好 ，不利于推广）如：?key1=val1&key2=val2
            // 2。路径参数（优雅，称为友好的URL，Friendly URL，利于推广）如：/User/GetModel/1
            [HttpGet("GetModel")]
            public ActionResult GetModel(int primaryKey)
            {
                var user = _storageRecord.GetModel(primaryKey);
                if (user == null)
                {
                    return new OkObjectResult(new
                    {
                        Code = 10000,
                        Msg = "查询失败",
                        Data = user
                    });
                }
                return new OkObjectResult(new
                {
                    Code = 200,
                    Msg = "查询成功",
                    Data = user
                });
            }
        }
    }

